import { useEffect, useState, Fragment } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import {
	Layout,
    Input,
	Spin,
	Radio,
	Modal,
	message,
} from 'antd'

import AvatorUpload from '../avatorUpload';
import {
	wrapper,
	header,
	header_wrapper,
	avator_wrapper,
	avator,
	avator_img,
	avator_upload_mask,
	header_introduce,
	username,
	name_input,
	userid,
	modify,
	content,
	content_introduce,
	content_sider,
	tip,
	setting_tip,
	introduction_txt,
	col,
	edit,
} from '../infoContent/index.module.css'
import { getUpdateName, getUpdateIntroduction, getUpdateGender } from '../../assets/js/api'
import { imgUrlDev, getToken, setToken } from '../../assets/js/tools'
import { changeUserInfo } from '../../store/actions'
import { publish } from 'pubsub-js';
import { showAvatorUpload } from '../../event-type';


const { Content, Sider } = Layout;
const { TextArea } = Input;


function SettingContent(props) {

    const { user: info, history, changeUserInfo } = props;

	const [stateInfo, setStateInfo] = useState(info);
	const [loading, setLoading] = useState(true);
	const [isCheckModalVisible, setCheckModalVisible] = useState(false);
	const [modalTips, setModalTips] = useState('是否提交修改');

	const [nameInput, setNameInput] = useState(info.name);
	const [genderInput, setGenderInput] = useState(info.gender);
	const [introductionInput, setIntroductionInput] = useState(info.introduction);

	const [updateAPI, setUpdateAPI] = useState(null);	// 使用对象形式,直接赋值会使promise直接调用
	const [changeVal, setChangeVal] = useState({});	

	useEffect(() => {
		if (info.id !== -1) {
			setLoading(false);

			setStateInfo(info);
			setNameInput(info.name);
			setGenderInput(info.gender);
			setIntroductionInput(info.introduction);
		}
	}, [info]);

	useEffect(() => {
		// 刷新setting页时,刚进入的gender是默认0,useState更新不是同步,会触发一次修改,而修改成的值就是默认0
		if (loading) return;
		// 更改值一样不修改,这个判断一个是不会触发的,因为相同值不会触发change
		if (info.gender === genderInput) return;

		const loadingTip = message.loading('提交中。。。');
		getUpdateGender({id: info.id, gender: genderInput})
		.then(res => {
			const {code, message: content, data, token} = res.data;
			const type = code === 1 ? 'success' : 'error';
			if (code === 1) {
				setStateInfo({...stateInfo, gender: genderInput});
				if (getToken('token')) {
					changeUserInfo(data);
					setToken('token', token);
				}
			}
			message.open({type, content});
		})
		.catch(err => {
			console.log(err);
			message.open({type: 'error',content: err});
		})
		.finally(() => {
			loadingTip();
		});
	}, [genderInput, info.id]);

    function comfirmModify() {
        // 完成修改
		let commitModify = false;
		if (nameInput !== stateInfo.name) {
			setChangeVal({ id: info.id, name: nameInput });
			handleOk();
			commitModify = true;
		}
		if (genderInput !== stateInfo.gender) {
			setChangeVal({ id: info.id, gender: genderInput });
			handleOk();
			commitModify = true;
		}
		if (introductionInput !== stateInfo.introduction) {
			setChangeVal({ id: info.id, intro: introductionInput });
			handleOk();
			commitModify = true;
		}
		if (commitModify) {
			return;
		}

		changeUserInfo(stateInfo);
		history.push({pathname: `/info/${info.id}`});
    }
	function comfirmCheck(changeVarStr, showModalTip = '是否提交修改') {
		// 修改确认
		let changeVar = null;
		let contrastVar = null;
		let useAPI = null;
		let paramStr = null;
		switch(changeVarStr) {
			case 'nameInput':
				changeVar = nameInput.trim();
				contrastVar = info.name;
				useAPI = getUpdateName;
				paramStr = 'name';
				break;
			case 'introductionInput':
				changeVar = introductionInput.trim();
				contrastVar = info.introduction;
				useAPI = getUpdateIntroduction;
				paramStr = 'introduction';
				break;
			default: 
				return;
		}
		if (contrastVar === changeVar) return;
		// 保存要使用的数据和提价api,在弹出框确认后调用
		setChangeVal({ id: info.id, [paramStr]: changeVar });
		setUpdateAPI({useAPI});		

		setCheckModalVisible(true);
		setModalTips(showModalTip);
	}
	function handleOk() {
		// 确认修改
		setCheckModalVisible(false);
		const loadingTip = message.loading('提交中。。。');

		updateAPI.useAPI(changeVal)
		.then(res => {
			const {code, message: content, data, token} = res.data;
			const type = code === 1 ? 'success' : 'error';
			if (code === 1) {
				if (getToken('token')) {
					changeUserInfo(data);
					setToken('token', token);
				}
				setStateInfo({...stateInfo, ...changeVal});
			}
			message.open({type, content});
		})
		.catch(err => {
			console.log(err);
			message.open({type: 'error',content: err});
		})
		.finally(() => {
			loadingTip();
		});
	}
	function handleCancel() {
		// 取消修改,复原数据
		setNameInput(info.name);
		setIntroductionInput(info.introduction);
		setCheckModalVisible(false);
	}


	return (
        <div className={wrapper}>
			{
				!loading ? '' :
				<div className="mask">
					<Spin spinning={loading} size='large' />
				</div>
			}
			<div className={header}>
				{
					loading ? '' :
					<div className={header_wrapper}>
						<div className={avator_wrapper} onClick={() => publish(showAvatorUpload, {type: 'user'})}>
							<div className={avator}>
								<img className={avator_img} src={imgUrlDev(info.avator)} alt="" />
								<div className={avator_upload_mask}>更新头像</div>
							</div>
						</div>
						<div className={header_introduce}>
							<p className={username}>
								<Input className={name_input}
									value={nameInput}
									size='large'
									maxLength={16}
									onChange={e => setNameInput(e.target.value)}
									onBlur={() => comfirmCheck('nameInput')}
								/>
							</p>
							<p className={userid}>id：{info.account}</p>
						</div>
						<div className={modify} onClick={comfirmModify}>完成</div>
					</div>
				}
			</div>
			<Layout className={content}>
				{ 
					loading ? 
						'' : 
						<Fragment>
							<Content className={content_introduce}>
								<div className={col}>
									<span className={[setting_tip, tip]}>性别：</span>
									<Radio.Group className={edit} 
										value={genderInput}
										buttonStyle="solid" 
										onChange={(e) => setGenderInput(e.target.value)}
									>
										<Radio.Button value="0">女</Radio.Button>
										<Radio.Button value="1">男</Radio.Button>
										<Radio.Button value="2">保密</Radio.Button>
									</Radio.Group>
								</div>
								<div className={col}>
									<span className={`${setting_tip} ${tip}`}>个人介绍：</span>
									<TextArea className={[introduction_txt, edit]} 
										value={introductionInput}
										showCount 
										maxLength={200}
										autoSize={true}
										onChange={e => setIntroductionInput(e.target.value)}
										onBlur={() => comfirmCheck('introductionInput')}
									/>
								</div>
							</Content>
							<Sider className={content_sider}></Sider>
						</Fragment>
					}
			</Layout>
			<Modal visible={isCheckModalVisible} onOk={handleOk} onCancel={handleCancel}>
				<span>{ modalTips }</span>
			</Modal>
			<AvatorUpload />
		</div>
    )
}


function mapStateToProps(state) {
	return {
		user: state.user,
	}
}

export default connect(
	mapStateToProps, 
	{
		changeUserInfo,
	}
)(withRouter(SettingContent));